<template>
  <el-tabs
    v-model="editableTabsValue"
    type="card"
    closable
    @tab-click="tabFun"
    @tab-remove="removeTab"
  >
    <el-tab-pane
      v-for="(item,index) in editableTabs"
      :key="index"
      :label="item.title"
      :name="item.name"
    >{{item.content}}</el-tab-pane>
  </el-tabs>
</template>

<script>
export default {
    name: "Tab",
    computed: {
    // 当前激活的选项卡
    editableTabsValue: {
      get() {
        return this.$store.state.MenuStore.editableTabsValue;
      },
      set(val) {
        this.$store.state.MenuStore.editableTabsValue = val;
      }
    },
    // tabs选项卡数据
    editableTabs: {
      get() {
        return this.$store.state.MenuStore.tabs;
      },
      set(val) {
        this.$store.state.MenuStore.tabs = val;
      }
    }
  },
  data() {
    return {
    };
  },
  methods: {
    // 点击选项卡
    tabFun(tab) {
      // 组装tabs数据
      let obj = {};
      if (tab.name === "desktop") {
        obj.title = "工作台";
      } else {
        obj.title = tab.label;
      }
      obj.name = tab.name;
      // 设置tabs数据
      this.$store.commit("selectMenu", obj);
      // 显示路由
      this.$router.push({ name: tab.name });
    },
    // 删除选项卡
    removeTab(targetName) {
      if (targetName === "desktop") {
        return;
      }
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
      // 存储当前打开的选项卡
       localStorage.setItem('tabList',JSON.stringify(this.editableTabs));
      // 存储当前激活的选项卡
      this.$store.commit('setActiveTabs',this.editableTabsValue);
     // 显示路由
      this.$router.push({ name: this.editableTabsValue });
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
